﻿using System;
using MySql.Data.MySqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections;

namespace Hammer_store
{

    /// <summary>
    /// Логика взаимодействия для Registration.xaml
    /// </summary>
    public partial class Registration : Window
    {
        internal bool[] successField = new bool[7] { false, false, false, false, false, false, false }; //Верные поля

        public Registration()
        {
            InitializeComponent();
            textBox_InputAge.MaxLength = 2;
            textBox_InputLogin.MaxLength = 30;
        }

        /* Событие-нажатие левой кнопки мыши: Перетаскивание окна */
        private void TitleBar_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
                this.DragMove();
        }

        /* Событие-нажатие по крестику: Закрытие окна */
        private void Image_cross_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Application exit = Application.Current;
            exit.Shutdown();
        }

        /* Событие-нажатие по картинке свернуть: Сворачивание окна */
        private void Image_colapso_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        /* Событие потеря фокуса: Поле логина */
        private void textBox_InputLogin_LostFocus(object sender, RoutedEventArgs e)
        {
            string loginLine = textBox_InputLogin.Text; //Присваивание введенной строки
            short existSymbol = 0;                      //Флажок для существования спец. символа

            if (loginLine != "")
            {
                //Проверка на существование числа
                if (Char.IsDigit(loginLine[0]))
                {
                    existSymbol = 2; //Присваиваем 2, чтобы появился полигон при проверке на спец. символ
                    textBox_InputLogin.BorderBrush = Brushes.Red;
                    ErrorMessagePolygon_Login.Visibility = Visibility.Visible;
                    labelErrorMessageOne_Login.Visibility = Visibility.Visible;
                }
                else
                {
                    ErrorMessagePolygon_Login.Visibility = Visibility.Hidden;
                    labelErrorMessageOne_Login.Visibility = Visibility.Hidden;
                };

                //Массив спец. символов
                char[] arraySymbols = {'!', '@', '#', '$', '%', '^', '&', '*', '(',
                                   ')', '-', '+', '=', '/', '|', '\\', '{', '}',
                                   '[', ']', ';', ':', '"', '\'', ',', '.', '<',
                                   '>', '?'};

                //Проверка на существование спец. символа в начале
                for (int i = 0; i < arraySymbols.Length; i++)
                {
                    if (loginLine[0] == arraySymbols[i])
                        existSymbol = 1;
                }

                if (existSymbol == 1)
                {
                    textBox_InputLogin.BorderBrush = Brushes.Red;
                    ErrorMessagePolygon_Login.Visibility = Visibility.Visible;
                    labelErrorMessageTwo_Login.Visibility = Visibility.Visible;
                }
                else if
                    (existSymbol == 0)
                {
                    ErrorMessagePolygon_Login.Visibility = Visibility.Hidden;
                    labelErrorMessageTwo_Login.Visibility = Visibility.Hidden;
                }

                //Проверка на существование логина из БД
                DB db = new DB();
                db.openConnection();
                MySqlCommand command = new MySqlCommand("SELECT login FROM Users", db.getConnection());
                MySqlDataReader reader = command.ExecuteReader();
                string loginsArray = "";
                while (reader.Read())
                {
                    loginsArray += reader[0].ToString();
                    loginsArray += " ";
                }
                reader.Close();
                db.closeConnection();

                if (loginsArray.Contains(loginLine))
                {
                    textBox_InputLogin.BorderBrush = Brushes.Red;
                    ErrorMessagePolygon_Login.Visibility = Visibility.Visible;
                    labelErrorMessageThree_Login.Visibility = Visibility.Visible;
                }
                else if (!loginsArray.Contains(loginLine) & existSymbol == 0)
                {
                    textBox_InputLogin.BorderBrush = Brushes.LimeGreen;
                    ErrorMessagePolygon_Login.Visibility = Visibility.Hidden;
                    labelErrorMessageThree_Login.Visibility = Visibility.Hidden;
                }

                if (loginLine.Length <= 3)
                {
                    textBox_InputLogin.BorderBrush = Brushes.Red;
                    ErrorMessagePolygon_Login.Visibility = Visibility.Visible;
                    labelErrorMessageFour_Login.Visibility = Visibility.Visible;
                }

                if (loginLine.Contains(" ") & existSymbol == 0)
                {
                    textBox_InputLogin.BorderBrush = Brushes.Red;
                    ErrorMessagePolygon_Login.Visibility = Visibility.Visible;
                    labelErrorMessageFive_Login.Visibility = Visibility.Visible;
                }

                //Проверка на верное поле
                if (textBox_InputLogin.BorderBrush == Brushes.LimeGreen) successField[0] = true;
                else successField[0] = false;
            }
        }


        /* Событие получение фокуса: Поле логина */
        private void textBox_InputLogin_GotFocus(object sender, RoutedEventArgs e)
        {
            textBox_InputLogin.BorderBrush = null;
            ErrorMessagePolygon_Login.Visibility = Visibility.Hidden;
            labelErrorMessageOne_Login.Visibility = Visibility.Hidden;
            labelErrorMessageTwo_Login.Visibility = Visibility.Hidden;
            labelErrorMessageThree_Login.Visibility = Visibility.Hidden;
            labelErrorMessageFour_Login.Visibility = Visibility.Hidden;
            labelErrorMessageFive_Login.Visibility = Visibility.Hidden;
        }


        /* Событие потеря фокуса: Поле почты */
        private void textBox_InputMail_LostFocus(object sender, RoutedEventArgs e)
        {
            string mailLine = textBox_InputMail.Text;
            short successStep = 0;                      //Флажок об успешном этапе

            if (mailLine != "")
            {
                //Проверка на существование в строке эт-коммерческой, точки и домена
                if (mailLine.Contains('@') & mailLine.Contains('.') &
                   (mailLine.Contains("mail") | mailLine.Contains("inbox") | mailLine.Contains("gmail")))
                {
                    successStep = 1;
                    textBox_InputMail.BorderBrush = Brushes.LimeGreen;
                    labelErrorMessageOne_Mail.Visibility = Visibility.Hidden;
                    ErrorMessagePolygon_Mail.Visibility = Visibility.Hidden;
                }
                else
                {
                    textBox_InputMail.BorderBrush = Brushes.Red;
                    labelErrorMessageOne_Mail.Visibility = Visibility.Visible;
                    ErrorMessagePolygon_Mail.Visibility = Visibility.Visible;
                }

                if (!mailLine.Contains('@') & !mailLine.Contains('.'))
                {
                    textBox_InputMail.BorderBrush = Brushes.Red;
                    labelErrorMessageOne_Mail.Visibility = Visibility.Visible;
                    ErrorMessagePolygon_Mail.Visibility = Visibility.Visible;
                }

                //Проверка на отсутствие символов кириллицы
                var cyrillic = Enumerable.Range(1024, 256).Select(ch => (char)ch);
                bool res = mailLine.Any(cyrillic.Contains);

                if (res == true)
                {
                    textBox_InputMail.BorderBrush = Brushes.Red;
                    labelErrorMessageOne_Mail.Visibility = Visibility.Visible;
                    ErrorMessagePolygon_Mail.Visibility = Visibility.Visible;
                }

                //Проверка на существование почты из БД
                DB db = new DB();
                db.openConnection();
                MySqlCommand command = new MySqlCommand("SELECT mail FROM Users", db.getConnection());
                MySqlDataReader reader = command.ExecuteReader();
                string mailsArray = "";
                while (reader.Read())
                {
                    mailsArray += reader[0].ToString();
                    mailsArray += " ";
                }
                reader.Close();
                db.closeConnection();

                if (mailsArray.Contains(mailLine))
                {
                    textBox_InputMail.BorderBrush = Brushes.Red;
                    ErrorMessagePolygon_Mail.Visibility = Visibility.Visible;
                    labelErrorMessageTwo_Mail.Visibility = Visibility.Visible;
                }
                else if (!mailsArray.Contains(mailLine) & successStep == 1 & res != true)
                {
                    textBox_InputMail.BorderBrush = Brushes.LimeGreen;
                    ErrorMessagePolygon_Mail.Visibility = Visibility.Hidden;
                    labelErrorMessageTwo_Mail.Visibility = Visibility.Hidden;
                }

                if (mailLine.Length <= 9 & successStep == 1 & res != true)
                {
                    textBox_InputMail.BorderBrush = Brushes.Red;
                    ErrorMessagePolygon_Mail.Visibility = Visibility.Visible;
                    labelErrorMessageOne_Mail.Visibility = Visibility.Visible;
                }

                if (mailLine.Contains(" "))
                {
                    textBox_InputMail.BorderBrush = Brushes.Red;
                    labelErrorMessageOne_Mail.Visibility = Visibility.Visible;
                    ErrorMessagePolygon_Mail.Visibility = Visibility.Visible;
                }

                //Проверка на верное поле
                if (textBox_InputMail.BorderBrush == Brushes.LimeGreen) successField[1] = true;
                else successField[1] = false;
            }
        }


        /* Событие получение фокуса: Поле почты */
        private void textBox_InputMail_GotFocus(object sender, RoutedEventArgs e)
        {
            textBox_InputMail.BorderBrush = null;
            ErrorMessagePolygon_Mail.Visibility = Visibility.Hidden;
            labelErrorMessageOne_Mail.Visibility = Visibility.Hidden;
            labelErrorMessageTwo_Mail.Visibility = Visibility.Hidden;
        }


        /* Событие потеря фокуса: Поле пароля */
        private void passwordBox_InputPass1_LostFocus(object sender, RoutedEventArgs e)
        {
            string passLine1 = passwordBox_InputPass1.Password;

            if (passLine1 != "")
            {
                //Проверка на содержание более 7 символов и отсутствие символов киррилицы
                var cyrillic = Enumerable.Range(1024, 256).Select(ch => (char)ch);
                bool res = passLine1.Any(cyrillic.Contains);

                if (res == true)
                {
                    passwordBox_InputPass1.BorderBrush = Brushes.Red;
                    labelErrorMessageOne_Pass1.Visibility = Visibility.Visible;
                    ErrorMessagePolygon_Pass1.Visibility = Visibility.Visible;
                }
                else if (res == false & passLine1.Length >= 7)
                {
                    passwordBox_InputPass1.BorderBrush = Brushes.LimeGreen;
                    labelErrorMessageOne_Pass1.Visibility = Visibility.Hidden;
                    ErrorMessagePolygon_Pass1.Visibility = Visibility.Hidden;
                }
                else if (res == false & passLine1.Length < 7)
                {
                    passwordBox_InputPass1.BorderBrush = Brushes.Red;
                    labelErrorMessageTwo_Pass1.Visibility = Visibility.Visible;
                    ErrorMessagePolygon_Pass1.Visibility = Visibility.Visible;
                }

                //Проверка на пробелы
                if (passLine1.Contains(" "))
                {
                    passwordBox_InputPass1.BorderBrush = Brushes.Red;
                    labelErrorMessageThree_Pass1.Visibility = Visibility.Visible;
                    ErrorMessagePolygon_Pass1.Visibility = Visibility.Visible;
                }
            }

            if (passwordBox_InputPass1.BorderBrush == Brushes.LimeGreen) successField[2] = true;
            else successField[2] = false;
        }


        /* Событие получение фокуса: Поле пароля */
        private void passwordBox_InputPass1_GotFocus(object sender, RoutedEventArgs e)
        {
            passwordBox_InputPass1.BorderBrush = null;
            ErrorMessagePolygon_Pass1.Visibility = Visibility.Hidden;
            labelErrorMessageOne_Pass1.Visibility = Visibility.Hidden;
            labelErrorMessageTwo_Pass1.Visibility = Visibility.Hidden;
            labelErrorMessageThree_Pass1.Visibility = Visibility.Hidden;
        }


        /* Скрыть первый глаз */
        private void Image_EyeHide1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            textBox_OutputPass1.Text = passwordBox_InputPass1.Password;
            textBox_OutputPass1.Visibility = Visibility.Visible;
            passwordBox_InputPass1.Visibility = Visibility.Hidden;
            Image_EyeHide1.Visibility = Visibility.Hidden;
            Image_EyeVisible1.Visibility = Visibility.Visible;
        }

        /* Показать первый глаз */
        private void Image_EyeVisible1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            passwordBox_InputPass1.Password = textBox_OutputPass1.Text;
            textBox_OutputPass1.Visibility = Visibility.Hidden;
            Image_EyeVisible1.Visibility = Visibility.Hidden;
            passwordBox_InputPass1.Visibility = Visibility.Visible;
            Image_EyeHide1.Visibility = Visibility.Visible;
        }

        /* Скрыть второй глаз */
        private void Image_EyeHide2_MouseDown(object sender, MouseButtonEventArgs e)
        {
            textBox_OutputPass2.Text = passwordBox_InputPass2.Password;
            textBox_OutputPass2.Visibility = Visibility.Visible;
            passwordBox_InputPass2.Visibility = Visibility.Hidden;
            Image_EyeHide2.Visibility = Visibility.Hidden;
            Image_EyeVisible2.Visibility = Visibility.Visible;
        }

        /* Показать второй глаз */
        private void Image_EyeVisible2_MouseDown(object sender, MouseButtonEventArgs e)
        {
            passwordBox_InputPass2.Password = textBox_OutputPass2.Text;
            textBox_OutputPass2.Visibility = Visibility.Hidden;
            Image_EyeVisible2.Visibility = Visibility.Hidden;
            passwordBox_InputPass2.Visibility = Visibility.Visible;
            Image_EyeHide2.Visibility = Visibility.Visible;
        }


        /* Событие потеря фокуса: Поле повторного пароля */
        private void passwordBox_InputPass2_LostFocus(object sender, RoutedEventArgs e)
        {
            string passLine1 = passwordBox_InputPass1.Password;
            string passLine2 = passwordBox_InputPass2.Password;

            //Проверка на соответствие
            if (passLine1 != "" & passLine2 != "")
            {
                if (passLine1 == passLine2)
                {
                    passwordBox_InputPass2.BorderBrush = Brushes.LimeGreen;
                }
                else if (passLine1 != passLine2)
                {
                    passwordBox_InputPass2.BorderBrush = Brushes.Red;
                    labelErrorMessage_Pass2.Visibility = Visibility.Visible;
                }
            }

            if (passwordBox_InputPass2.BorderBrush == Brushes.LimeGreen) successField[3] = true;
            else successField[3] = false;
        }


        /* Событие получение фокуса: Поле повторного пароля */
        private void passwordBox_InputPass2_GotFocus(object sender, RoutedEventArgs e)
        {
            passwordBox_InputPass2.BorderBrush = null;
            labelErrorMessage_Pass2.Visibility = Visibility.Hidden;
        }


        /* Событие потеря фокуса: Поле имени */
        private void textBox_Input_FName_LostFocus(object sender, RoutedEventArgs e)
        {
            string name = textBox_Input_FName.Text;

            if (name != "")
            {
                if (name.Length < 3)
                {
                    textBox_Input_FName.BorderBrush = Brushes.Red;
                    ErrorMessagePolygon_Name.Visibility = Visibility.Visible;
                    labelErrorMessageOne_Name.Visibility = Visibility.Visible;
                }
                else if (name.Length >= 3 & !name.Contains(" "))
                {
                    textBox_Input_FName.BorderBrush = Brushes.LimeGreen;
                    ErrorMessagePolygon_Name.Visibility = Visibility.Hidden;
                    labelErrorMessageOne_Name.Visibility = Visibility.Hidden;
                }
                else if (name.Contains(" "))
                {
                    textBox_Input_FName.BorderBrush = Brushes.Red;
                    ErrorMessagePolygon_Name.Visibility = Visibility.Visible;
                    labelErrorMessageTwo_Name.Visibility = Visibility.Visible;
                }
            }

            if (textBox_Input_FName.BorderBrush == Brushes.LimeGreen) successField[4] = true;
            else successField[4] = false;
        }


        /* Событие получение фокуса: Поле имени */
        private void textBox_Input_FName_GotFocus(object sender, RoutedEventArgs e)
        {
            textBox_Input_FName.BorderBrush = null;
            ErrorMessagePolygon_Name.Visibility = Visibility.Hidden;
            labelErrorMessageOne_Name.Visibility = Visibility.Hidden;
            ErrorMessagePolygon_Name.Visibility = Visibility.Hidden;
            labelErrorMessageTwo_Name.Visibility = Visibility.Hidden;
        }


        /* Событие-нажатие: Обработчик Имени */
        private void textBox_Input_FName_KeyDown(object sender, KeyEventArgs e)
        {
            if (!(e.Key >= Key.A) || !(e.Key <= Key.Z)) e.Handled = true;
            if (e.Key == Key.Space) e.Handled = true;

        }


        /* Событие потеря фокуса: Поле фамилии */
        private void textBox_Input_LName_LostFocus(object sender, RoutedEventArgs e)
        {
            string surname = textBox_Input_LName.Text;

            if (surname != "")
            {
                if (surname.Length < 3)
                {
                    textBox_Input_LName.BorderBrush = Brushes.Red;
                    ErrorMessagePolygon_Surname.Visibility = Visibility.Visible;
                    labelErrorMessageOne_Surname.Visibility = Visibility.Visible;
                }
                else if (surname.Length >= 3 & !surname.Contains(" "))
                {
                    textBox_Input_LName.BorderBrush = Brushes.LimeGreen;
                    ErrorMessagePolygon_Surname.Visibility = Visibility.Hidden;
                    labelErrorMessageOne_Surname.Visibility = Visibility.Hidden;
                }
                else if (surname.Contains(" "))
                {
                    textBox_Input_LName.BorderBrush = Brushes.Red;
                    ErrorMessagePolygon_Surname.Visibility = Visibility.Visible;
                    labelErrorMessageTwo_Surname.Visibility = Visibility.Visible;
                }
            }

            if (textBox_Input_LName.BorderBrush == Brushes.LimeGreen) successField[5] = true;
            else successField[5] = false;
        }


        /* Событие получение фокуса: Поле фамилии */
        private void textBox_Input_LName_GotFocus(object sender, RoutedEventArgs e)
        {
            textBox_Input_LName.BorderBrush = null;
            ErrorMessagePolygon_Surname.Visibility = Visibility.Hidden;
            labelErrorMessageOne_Surname.Visibility = Visibility.Hidden;
            labelErrorMessageTwo_Surname.Visibility = Visibility.Hidden;
        }


        /* Событие-нажатие: Обработчик Фамилии */
        private void textBox_Input_LName_KeyDown(object sender, KeyEventArgs e)
        {
            if (!(e.Key >= Key.A) || !(e.Key <= Key.Z)) e.Handled = true;
            if (e.Key == Key.Space) e.Handled = true;
        }


        /* Событие потеря фокуса: Поле возраста */
        private void textBox_InputAge_LostFocus(object sender, RoutedEventArgs e)
        {
            if (textBox_InputAge.Text != "")
            {
                int age = Convert.ToInt32(textBox_InputAge.Text);

                if (age < 6 | age > 90)
                {
                    textBox_InputAge.BorderBrush = Brushes.Red;
                    ErrorMessagePolygon_Age.Visibility = Visibility.Visible;
                    labelErrorMessage_Age.Visibility = Visibility.Visible;
                }
                else
                {
                    textBox_InputAge.BorderBrush = Brushes.LimeGreen;
                    ErrorMessagePolygon_Age.Visibility = Visibility.Hidden;
                    labelErrorMessage_Age.Visibility = Visibility.Hidden;
                }

                if (textBox_InputAge.BorderBrush == Brushes.LimeGreen) successField[6] = true;
                else successField[6] = false;
            }
        }


        /* Событие получение фокуса: Поле возраста */
        private void textBox_InputAge_GotFocus(object sender, RoutedEventArgs e)
        {
            textBox_InputAge.BorderBrush = null;
            ErrorMessagePolygon_Age.Visibility = Visibility.Hidden;
            labelErrorMessage_Age.Visibility = Visibility.Hidden;
        }


        /* Событие-нажатие: Обработчик возраста */
        private void textBox_InputAge_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key < Key.D0 || e.Key > Key.D9) e.Handled = true;
        }


        /* Событие-нажатие: Увеличение возраста на единицу */
        private void buttonUp_Click(object sender, RoutedEventArgs e)
        {
            if (textBox_InputAge.Text != "")
            {
                int numAge = Convert.ToInt32(textBox_InputAge.Text);
                if (numAge != 90)
                {
                    numAge++;
                    textBox_InputAge.Text = numAge.ToString();
                }
            }
            else if (textBox_InputAge.Text == "")
            {
                textBox_InputAge.Text = "0";
                int numAge = Convert.ToInt32(textBox_InputAge.Text);
                if (numAge != 90)
                {
                    numAge++;
                    textBox_InputAge.Text = numAge.ToString();
                }
            }
        }


        /* Событие-нажатие: Уменьшение возраста на единицу */
        private void buttonDown_Click(object sender, RoutedEventArgs e)
        {
            if (textBox_InputAge.Text != "")
            {
                int numAge = Convert.ToInt32(textBox_InputAge.Text);
                if (numAge != 6)
                {
                    numAge--;
                    textBox_InputAge.Text = numAge.ToString();
                }
            }
        }


        /* Событие-нажатие: клавиша вверх и вниз (увеличение и уменьшение возраста на единицу) */
        private void textBox_InputAge_KeyUp(object sender, KeyEventArgs e)
        {
            if (textBox_InputAge.Text != "")
            {
                int numAge = Convert.ToInt32(textBox_InputAge.Text);
                if (e.Key == Key.Up)
                {
                    numAge++;
                    textBox_InputAge.Text = numAge.ToString();
                }
                else if (e.Key == Key.Down)
                {
                    numAge--;
                    textBox_InputAge.Text = numAge.ToString();
                }
            }
        }


        /* Событие-кнопка: Готово */
        private void button_ready_Click(object sender, RoutedEventArgs e)
        {
            DB db = new DB();
            string sql = "INSERT INTO `Users` (`login`, `pass`, `name`, `surname`, `age`, `mail`) VALUES (@login, @pass, @name, @surname, @age, @mail)";

            //Передаем объекту команду для вставки данных в таблицу Users 
            MySqlCommand command = new MySqlCommand(sql, db.getConnection());

            //Добавляем записи в столбцы
            command.Parameters.Add("@login", MySqlDbType.VarChar).Value = textBox_InputLogin.Text;
            command.Parameters.Add("@pass", MySqlDbType.VarChar).Value = passwordBox_InputPass1.Password;
            command.Parameters.Add("@name", MySqlDbType.Text).Value = textBox_Input_FName.Text;
            command.Parameters.Add("@surname", MySqlDbType.Text).Value = textBox_Input_LName.Text;
            command.Parameters.Add("@age", MySqlDbType.Int32).Value = textBox_InputAge.Text;
            command.Parameters.Add("@mail", MySqlDbType.VarChar).Value = textBox_InputMail.Text;

            db.openConnection(); //Открываем соединение с БД

            //Передача запроса
            string message = "";
            foreach (bool elem in successField)
            {
                if (elem == false)
                    message = "Есть пустое поле";
            }

            if (message == "")
            {
                if (command.ExecuteNonQuery() == 1) //Если строка обработалась, то возвратиться '1'
                {
                    MessageBox.Show("Аккаунт создан");

                    Authorization showAuthorization = new Authorization();
                    showAuthorization.Show();
                    this.Hide();
                }
            }
            else MessageBox.Show("Ошибка при регистрации!");

            db.closeConnection(); //Закрыть соединение с БД
        }


        /* Событие-кнопка Назад: Вернуться на UserVerification */
        private void button_backOnUserVerification_Click(object sender, RoutedEventArgs e)
        {
            Begin_UserVerification showUserVerifiation = new Begin_UserVerification();
            showUserVerifiation.Show();
            this.Hide();
        }

    }
}

    

